# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(ropls)
library(optparse)
library(tidyverse)
library(magrittr)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

p.cor <- function(n, p, method="pearson"){
    df <- n - 2
    t <- qt(p / 2, df, lower.tail = FALSE)
    r <- switch(method,
    "pearson" = sqrt(t ^ 2 / (df + t ^ 2))
    )
    return(r)
}

option_list <- list(
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--config", default = "config.csv", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
select(c("SampleID", "ClassNote"))

configData <- read.csv(opt$config, header = F, stringsAsFactors = F) %>%
    set_colnames(c("arg", "value")) %>%
    column_to_rownames("arg")

configData

vipNum <- configData["oplsda.vip", "value"] %>%
as.numeric()

parent <- paste0("./")
createWhenNoExist(parent)
allFileName <- paste0(parent, "/OPLSDA_VIP.csv")
outFileName <- paste0(parent, "/OPLSDA_VPlot_without_Label.pdf")
method <- "pearson"
n <- nrow(sampleInfo)
plotData <- read.csv(allFileName, header = T) %>%
    select(- c("Class")) %>%
    rowwise() %>%
    do({
        result <- as.data.frame(.)
        p <- result["P"]
        vip <- result["VIP"]
        col <- if (vip >= vipNum) {
            "height"
        }else "low"
        result$col <- col
        result
    }) %>%
    mutate(col = factor(col, levels = c("height", "median", "low"))) %>%
    rename(vip = VIP, cor = Corr.Coeffs.) %>%
    as.data.frame()

print(head(plotData))

yMax <- max(plotData$vip)
breaks <- seq(- 1, 1, 0.2)
fontSize <- 1.5

pointCols <- tibble(sig = c("height", "median", "low"), col = c("#006400", "#0000FF", "grey")) %>%
  deframe()

p <- ggplot(plotData, mapping = aes(x = cor, y = vip)) +
    theme_bw(base_size = 8.8, base_family = "Times") +
    theme(axis.text.x = element_text(size = 9, vjust = 0.5),
    axis.text.y = element_text(size = 8.8), legend.position = 'none',
    axis.title.y = element_text(size = 11), legend.margin = margin(t = 0.3, b = 0.1, unit = 'cm'),
    legend.text = element_text(size = 6), axis.title.x = element_text(size = 11), panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(), plot.title = element_text(hjust = 0.5, size = 13)
    ) +
    ylab("VIP") +
    geom_hline(aes(yintercept = vipNum), colour = "#A9A9A9", linetype = 2, size = 0.375) +
    scale_colour_manual("", values = pointCols) +
    scale_x_continuous("Corr.Coeffs.", breaks = breaks, limits = c(- 1.2, 1.2)) +
    geom_text(aes(x = cor, y = vip, colour = col), label = "+", size = 4, family = "Times",
    hjust = 0.5, vjust = 0.3, fontface = "bold") 



ggsave(limitsize = FALSE,outFileName, p, width = 6, height = 4)











